/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;

using Gtk;
using Glade;
using Mono.Unix;

using DCSharp.Backend.Connections;
using DCSharp.Backend.Managers;
using DCSharp.Backend.Objects;
using DCSharp.Xml;

namespace DCSharp.Gui
{
	public class ListDownloadStatusArea : MessageArea
	{
		private ListDownloader downloader;

		private ProgressBar progressBar;
		private uint timeout;

		public ListDownloadStatusArea(ListDownloader downloader) :
			base(null, null, MessageType.Info)
		{
			if (downloader == null)
			{
				throw new ArgumentNullException("downloader");
			}

			progressBar = new ProgressBar();
			progressBar.PulseStep = 0.01;
			progressBar.Show();
			VBox.PackEnd(progressBar, false, false, 0);

			Downloader = downloader;
		}

		#region Properties

		public ListDownloader Downloader
		{
			get { return downloader; }
			set
			{
				if (downloader != null)
				{
					downloader.ListReceived -= OnStatusChanged;
					downloader.StateChanged -= OnStatusChanged;
					downloader.User.OnlineChanged -= OnStatusChanged;
				}

				downloader = value;
				if (downloader != null)
				{
					downloader.ListReceived += OnStatusChanged;
					downloader.StateChanged += OnStatusChanged;
					downloader.User.OnlineChanged += OnStatusChanged;
				}
				UpdateStatus();
			}
		}

		#endregion

		#region Methods

		protected override void OnDestroyed()
		{
			ListDownloader ld = downloader;
			if (ld != null)
			{
				Downloader = null;
				ld.Stop();
			}
			RemoveTimeout();
			base.OnDestroyed();
		}

		private void UpdateStatus()
		{
			RemoveTimeout();
			if (downloader == null)
			{
				Update(Catalog.GetString("Waiting..."), null, false);
				return;
			}

			if (downloader.Result != null)
			{
				Update(Catalog.GetString("File list loaded"), null, false);
			}
			else if (downloader.State == DownloadState.Stopped)
			{
				Exception exception = downloader.Exception;
				string secondary = exception != null ? exception.Message : null;

				Update(GetErrorMessage(downloader.Error), secondary, true);
			}
			else if (!downloader.User.IsOnline)
			{
				Update(Catalog.GetString("User offline"), null, false);
			}
			else // Idle or loading
			{
				string status = downloader.Progress == 1 ?
					Catalog.GetString("Loading...") : Util.GetStatus(downloader);

				if (timeout == 0)
				{
					timeout = GLib.Timeout.Add(10, OnProgressTimeout);
				}
				Update(status, null, false);
			}
		}

		private static string GetErrorMessage(ListDownloadError error)
		{
			switch (error)
			{
				case ListDownloadError.InvalidList:
					return Catalog.GetString("Could not open the list");

				case ListDownloadError.ListNotAvailable:
					return Catalog.GetString("This user does not support list browsing");

				default:
					return Catalog.GetString("Error downloading list");
			}
		}

		private void Update(string primary, string secondary, bool isError)
		{
			PrimaryText = primary;
			SecondaryText = secondary;
			MessageType = isError ? MessageType.Error : MessageType.Info;

			progressBar.Visible = timeout != 0;
		}

		private void RemoveTimeout()
		{
			if (timeout != 0)
			{
				GLib.Source.Remove(timeout);
				timeout = 0;

				progressBar.Fraction = 0;
			}
		}

		private bool OnProgressTimeout()
		{
			if (downloader.State == DownloadState.Active)
			{
				progressBar.Fraction = downloader.Progress;
				progressBar.Text = String.Format(
					Catalog.GetString("{0} of {1} downloaded, about {2} left"),
					Util.FormatFileSize((long)(downloader.Progress * downloader.FileSize)),
					Util.FormatFileSize(downloader.FileSize),
					downloader.GetRemainingTime());
			}
			else if (downloader.State == DownloadState.Loading)
			{
				double progress = downloader.LoadingProgress;

				progressBar.Fraction = progress;
				progressBar.Text = String.Format(
					Catalog.GetString("{0} of {1} loaded"),
					Util.FormatFileSize((long)(progress * downloader.FileSize)),
					Util.FormatFileSize(downloader.FileSize));
			}
			else
			{
				// Waiting
				progressBar.Pulse();
				progressBar.Text = null;
			}
			return true;
		}

		private void OnStatusChanged(object obj, EventArgs args)
		{
			Application.Invoke(delegate
			{
				UpdateStatus();
			});
		}

		#endregion
	}
}
